// pages/exhibition/my-reservations/my-reservations.js
Page({
  data: {
    activeFilter: 'all',
    allReservations: [
      {
        id: 1,
        sessionId: 1,
        sessionTitle: '生命教育主题展',
        sessionDate: '2025.08.20',
        sessionTime: '09:00-11:00',
        location: '生命教育展馆A厅',
        reservationDate: '2025.08.15',
        reservationTime: '14:30',
        reservationCode: 'EX20250820001',
        status: 'confirmed',
        statusText: '已确认',
        remark: '希望了解生命教育相关内容'
      },
      {
        id: 2,
        sessionId: 3,
        sessionTitle: '医学知识科普展',
        sessionDate: '2025.08.25',
        sessionTime: '10:00-12:00',
        location: '生命教育展馆C厅',
        reservationDate: '2025.08.18',
        reservationTime: '16:20',
        reservationCode: 'EX20250825002',
        status: 'checked_in',
        statusText: '已签到',
        remark: ''
      },
      {
        id: 3,
        sessionId: 2,
        sessionTitle: '捐献者故事分享会',
        sessionDate: '2025.08.22',
        sessionTime: '14:00-16:00',
        location: '生命教育展馆B厅',
        reservationDate: '2025.08.16',
        reservationTime: '10:15',
        reservationCode: 'EX20250822003',
        status: 'cancelled',
        statusText: '已取消',
        remark: '临时有事无法参加'
      }
    ],
    reservations: []
  },

  onLoad(options) {
    console.log('我的预约页面加载');
    this.loadReservations();
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadReservations();
  },

  // 加载预约数据
  loadReservations() {
    // 这里可以从服务器获取用户预约数据
    console.log('加载预约数据');
    this.filterReservations();
  },

  // 筛选预约
  filterReservations() {
    const { allReservations, activeFilter } = this.data;
    let filteredReservations = allReservations;

    if (activeFilter !== 'all') {
      filteredReservations = allReservations.filter(item => item.status === activeFilter);
    }

    this.setData({
      reservations: filteredReservations
    });
  },

  // 设置筛选条件
  setFilter(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({
      activeFilter: filter
    });
    this.filterReservations();
  },

  // 查看场次详情
  viewSessionDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/exhibition/session-detail/session-detail?id=${id}`
    });
  },

  // 签到功能
  checkIn(e) {
    const id = e.currentTarget.dataset.id;
    const reservation = this.data.allReservations.find(item => item.id == id);
    
    if (!reservation) {
      wx.showToast({
        title: '预约信息不存在',
        icon: 'none'
      });
      return;
    }

    if (reservation.status !== 'confirmed') {
      wx.showToast({
        title: '预约状态异常',
        icon: 'none'
      });
      return;
    }

    // 调用扫码签到
    wx.scanCode({
      success: (res) => {
        console.log('扫码结果:', res);
        this.processCheckIn(reservation, res.result);
      },
      fail: (err) => {
        console.log('扫码失败:', err);
        wx.showToast({
          title: '扫码失败',
          icon: 'none'
        });
      }
    });
  },

  // 处理签到
  processCheckIn(reservation, scanResult) {
    wx.showLoading({
      title: '签到中...'
    });

    // 模拟签到处理
    setTimeout(() => {
      wx.hideLoading();
      
      // 这里应该验证扫码结果是否匹配预约码
      if (scanResult === reservation.reservationCode) {
        // 更新预约状态
        const updatedReservations = this.data.allReservations.map(item => {
          if (item.id === reservation.id) {
            return {
              ...item,
              status: 'checked_in',
              statusText: '已签到'
            };
          }
          return item;
        });

        this.setData({
          allReservations: updatedReservations
        });

        this.filterReservations();

        wx.showToast({
          title: '签到成功',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: '预约码不匹配',
          icon: 'none'
        });
      }
    }, 1500);
  },

  // 取消预约
  cancelReservation(e) {
    const id = e.currentTarget.dataset.id;
    const reservation = this.data.allReservations.find(item => item.id == id);
    
    if (!reservation) {
      wx.showToast({
        title: '预约信息不存在',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '确认取消',
      content: `确定要取消预约"${reservation.sessionTitle}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.processCancelReservation(reservation);
        }
      }
    });
  },

  // 处理取消预约
  processCancelReservation(reservation) {
    wx.showLoading({
      title: '取消中...'
    });

    setTimeout(() => {
      wx.hideLoading();
      
      // 更新预约状态
      const updatedReservations = this.data.allReservations.map(item => {
        if (item.id === reservation.id) {
          return {
            ...item,
            status: 'cancelled',
            statusText: '已取消'
          };
        }
        return item;
      });

      this.setData({
        allReservations: updatedReservations
      });

      this.filterReservations();

      wx.showToast({
        title: '取消成功',
        icon: 'success'
      });
    }, 1000);
  },

  // 跳转到场次页面
  goToSessions() {
    wx.navigateTo({
      url: '/pages/exhibition/sessions/sessions'
    });
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '我的展馆预约',
      path: '/pages/exhibition/my-reservations/my-reservations'
    };
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadReservations();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  }
});
